/**
 * // Definition for a Node.
 * function Node(val, left, right, next) {
 *    this.val = val === undefined ? null : val;
 *    this.left = left === undefined ? null : left;
 *    this.right = right === undefined ? null : right;
 *    this.next = next === undefined ? null : next;
 * };
 */

/**
 * @param {Node} root
 * @return {Node}
 */
var connect = function(root) {
    if(root == null) return root
    let dp = []
    dp.push(root)
    while(dp.length !== 0) {
        let temp = dp
        dp = []
        let i
        for(i = 0; i < temp.length; i++) {
            if(i === temp.length - 1) {
                temp[i] = null
            } else {
                temp[i].next = temp[i + 1]
            }
            if(temp[i].left) dp.push(temp[i].left)
            if(temp[i].right) dp.push(temp[i].right)
        }
    }
    return root
};